<template>
  <div class="authorization" v-if="!loading">
    <slot/>
  </div>
  <van-loading v-else size="24px" class="page-loading">加载中…</van-loading>
</template>
<script>
import { mapActions } from 'vuex'
import { handleAuth, redirectLink, getWxAuthUrl, isWxBrowser } from '@/utils/work-weixin'

export default {
  name: 'Authorization',
  data() {
    return {
      loading: true,
    }
  },
  created() {
    const data = handleAuth()
    this.handleWxAccredit(data)
  },
  methods: {
    ...mapActions('workWeixin', [
      'fetchWxUserInfo',
      'getEmployeeInfo',
      'qryCurrentPageHasBeenAuthorized'
    ]),

    handleWxAccredit(appInfo) {
      const { code } = this.$route.query

      if (isWxBrowser().isWxWork) { // 企微
        if (code) {
          console.log(1234567, code)
          this.loading = false
          const data = {
            code: code
          }
          this.getEmployeeInfo({ data }).then(res => {
            localStorage.setItem('userid', res.data.userid)
            localStorage.setItem('user_ticket', res.data.user_ticket)
          }).catch(err => {
            console.log('获得用户信息失败', err)
          })
        } else {
          redirectLink(appInfo)
        }
      } else if (isWxBrowser().isWx) { // 个微
        if (code) { // 获得微信用户的个人信息
          this.getWxUserInfoByCode(code)
        } else {
          this.handleToWxAuth()
        }
      } else { // 提示在微信/企业微信中打开应用
        this.$toast('抱歉, 请在微信或者企业微信中打开本应用！')
        this.loading = false
      }
    },

    // 获取企微员工基本信息
    getUserInfo(code) {
      return this.getEmployeeInfo({
        params: {
          deviceId: +new Date(),
          userTicket: code
        }
      })
        .then(res => {
          const { data, statusCode, message } = res
          if (statusCode === 200) {
            localStorage.setItem('EMPLOYEE_ID', data.userId)
            localStorage.setItem('EMPLOYEE_TOKEN', data.token)
            localStorage.setItem('code', code)
            // 通知全局当前用户鉴权完毕
            window.postMessage({ msg: 'getUserInfo:ok' }, window.location.origin)
            this.loading = false
            return data
          } else {
            this.$router.push({
              name: 'error-page',
              query: {
                tip: message
              }
            })
          }
        })
    },

    // 获取个人微信用户信息
    getWxUserInfoByCode(code) {
      return this.fetchWxUserInfo({
        params: {
          code
        }
      }).then(wxUserInfoRes => {
        const { statusCode, data, message } = wxUserInfoRes
        if (statusCode === 200) {
          // 缓存用户信息
          localStorage.setItem('currentUserInfo', JSON.stringify(data))
          localStorage.setItem('currentUnionId', JSON.stringify(data.unionId))
          return data
        } else {
          console.log(message)
        }
      })
    },

    handleToWxAuth() {
      window.location.replace(getWxAuthUrl())
    },

  }
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
